package edu.washington.ling.syntric.proc;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;

import edu.washington.ling.syntric.io.ExampleDoc;
import edu.washington.ling.syntric.io.ExampleDocReader;
import edu.washington.ling.syntric.io.ExampleDocWriter;
import edu.washington.ling.syntric.io.Example;
import edu.washington.ling.syntric.struct.error.PrintingExceptionHandler;

public class ConvertExamplesToLaTeX {
	
	private static ConvertExamplesToLaTeXOptions opts = new ConvertExamplesToLaTeXOptions();
	private static PrintingExceptionHandler pHandler = new PrintingExceptionHandler();
	
	private static void convertExamplesToLaTeXInFile(){
		int numExamples = 0;
		try {
			ExampleDocReader exfr = ExampleDocReader.newReader(opts.inputFilePath, "xml");
			ExampleDoc exf = exfr.read();
			ExampleDocWriter exfw = ExampleDocWriter.newWriter(opts.outputFilePath, "latex");
			List<String> ids = new LinkedList<String>(exf.getIDs());
			Collections.sort(ids);
			for (String id: ids) {
				numExamples++;
				Example exr = exf.getExampleWithID(id);
				List<String> includeLayerList = opts.includeLayers;
				String[] includeLayers = includeLayerList.toArray(new String[includeLayerList.size()]);
				exfw.writeExample(exr, includeLayers);
			}
			exfw.close();
			System.out.println("Convert examples to LaTeX was successful.");
			System.out.println(String.format("Processed %d total examples", numExamples));
		} 
		catch(Exception e) {
			pHandler.handle(e, "Convert examples to LaTeX failed.", System.out);
			e.printStackTrace(System.out);
			System.exit(-1);
		}
	}

	public static void main(String[] args) {
		CmdLineParser parser = new CmdLineParser(opts);
		try {
			parser.parseArgument(args);
			convertExamplesToLaTeXInFile();
		}
		catch(CmdLineException e) {
			System.out.println(e.getMessage());
			System.out.print("Usage: ConvertExamplesToLaTeX");
			parser.printSingleLineUsage(System.out);
			System.out.println();
			parser.printUsage(System.out);
			System.exit(-1);
		}
	}
}
